package top.codingfly.util;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;

import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

public class AesUtils {

    public static void main(String[] args) {
        String encryptData = encryptFromString("12775616", Mode.CBC, Padding.ZeroPadding, "codingfly0123456", "0123456codingfly");
        System.out.println("加密：" + encryptData);
        String decryptData = decryptFromString(encryptData, Mode.CBC, Padding.ZeroPadding, "codingfly0123456", "0123456codingfly");
        System.out.println("解密：" + decryptData);
    }

    public static String encryptFromString(String data, Mode mode, Padding padding, String aesKey, String iv) {
        AES aes;
        if (Mode.CBC == mode) {
            aes = new AES(mode, padding, new SecretKeySpec(aesKey.getBytes(), "AES"), new IvParameterSpec(iv.getBytes()));
        } else {
            aes = new AES(mode, padding, new SecretKeySpec(aesKey.getBytes(), "AES"));
        }
        return aes.encryptBase64(data, StandardCharsets.UTF_8);
    }

    public static String decryptFromString(String data, Mode mode, Padding padding, String aesKey, String iv) {
        AES aes;
        if (Mode.CBC == mode) {
            aes = new AES(mode, padding, new SecretKeySpec(aesKey.getBytes(), "AES"), new IvParameterSpec(iv.getBytes()));
        } else {
            aes = new AES(mode, padding, new SecretKeySpec(aesKey.getBytes(), "AES"));
        }
        byte[] decryptDataBase64 = aes.decrypt(data);
        return new String(decryptDataBase64, StandardCharsets.UTF_8);
    }

}